
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Collections.Generic;
using System.Text;

using Swaf;
using Swaf.BizObj;
using Swaf.BizRule;
using Swaf.Container;
using Swaf.Security;

namespace Reservations
{
	public class ReservationBizRules : Syrinx.BaseBizRules
	{
		public IBizObjList getReservations(IApplication app, IRuleContext context, object resultValue, object[] inputParams)
		{
			return resultValue as IBizObjList;
		}

		public IBizObj getReservationDetails(IApplication app, IRuleContext context, object resultValue, object[] inputParams)
		{
			IBizObj salesOrder = resultValue as IBizObj;
			if (salesOrder != null && (bool)ActiveCompany.get("limits.usingReservations"))
			{
				IBizObj reservation = app.appData.get("DA.Reservations.GetReservationDetails", salesOrder) as IBizObj;
				if (reservation != null)
				{
					DateTime ad = (DateTime)reservation.get("arrivalDate");
					DateTime dd = (DateTime)reservation.get("departureDate");
					TimeSpan t = dd - ad;
					reservation.put("numDaysStay", t.Days);
					if (Cmn.IsEmpty(reservation.get("flightInfo.arrivalFlightNumber")))
					{
						reservation.put("flightInfo.flightArrival", ad.AddSeconds(1));
						reservation.put("flightInfo.flightDeparture", dd.AddSeconds(1));
					}
					reservation.clearDirtyFlags();
					salesOrder.put("reservation", reservation);
				}
			}
			return salesOrder;
		}

		public List<Swaf.Gui.UserMessage> validateReservation(IApplication app, IRuleContext context, IBizObj reservation)
		{
			List<Swaf.Gui.UserMessage> msgs = null;

			List<ValidationError> errors = reservation.validate();
			if (!(errors == null || errors.Count == 0))
			{
				msgs = new List<Swaf.Gui.UserMessage>();
				foreach (ValidationError e in errors)
					msgs.Add(new Swaf.Gui.UserMessage("Error-InvalidParameter", e));
				return msgs;
			}

			FlexiMap m = new FlexiMap();
			DateTime checkin = (DateTime)reservation.get("arrivalDate");
			int numNights = (int)reservation.get("numDaysStay");

			int maxNights = (int)ActiveCompany.get("settings.resMaxNightStay");
			int maxMonthsOut = (int)ActiveCompany.get("settings.resMaxCheckinNumMonthsOut");

			if (checkin < DateTime.Now || maxNights < numNights || DateTime.Now.AddMonths(maxMonthsOut) < checkin)
			{
				m.put("resMaxNightStay", maxNights);
				m.put("resMaxCheckinNumMonthsOut", maxMonthsOut);
				msgs = new List<Swaf.Gui.UserMessage>();
				if (checkin < DateTime.Now)
					msgs.Add(new Swaf.Gui.UserMessage("Error-ReservationInPast", m));
				if (maxNights < numNights)
					msgs.Add(new Swaf.Gui.UserMessage("Error-ReservationTooLong",m));
				if (DateTime.Now.AddMonths(maxMonthsOut) < checkin)
					msgs.Add(new Swaf.Gui.UserMessage("Error-ReservationTooFarAway",m));
			}

			if (msgs == null)
			{
				//Check on availability given reservation information.  They may have changed their checkin/out dates.
				IBizObjList salesOrderItems = (IBizObjList)context.RuleGroup.execute(context, "getSalesOrderItems", reservation.get("id")).CallResults;
				if (salesOrderItems != null)
				{
					foreach(IBizObj item in salesOrderItems)
						if (((string)item.get("product.partId")).StartsWith("RT-"))
						{
							IResults rc = context.RuleGroup.execute(context, "isRoomAvailableToUser",
										checkin, reservation.get("departureDate"), item.get("product.partId"), item.get("quantity"));
							string[] availabilityInfo = (string[])rc.CallResults;
							if (availabilityInfo != null)
							{
								msgs = new List<Swaf.Gui.UserMessage>();
								m.put("roomTitle", item.get("product.title"));
								m.put("reasonDate", availabilityInfo);
								m.put("quantityAvailable", availabilityInfo[1]);
								msgs.Add(new Swaf.Gui.UserMessage("Error-RoomNotAvailabeOnDesiredDate", m));
								break;
							}
						}
				}
			}

			return msgs;
		}

		public eCom.SalesOrderEditLevel getReservationSalesOrderEditLevel(IApplication app, IRuleContext context, object resultValue, object[] inputParams)
		{
			eCom.SalesOrderEditLevel editLevel = (eCom.SalesOrderEditLevel)resultValue;
			if (editLevel != eCom.SalesOrderEditLevel.none)
			{
				IBizObj salesOrder = ((IRuleContext)inputParams[1]).get("salesOrder") as IBizObj;
				if (salesOrder != null)
				{
					DateTime checkIn = (DateTime)salesOrder.get("reservation.arrivalDate");
					if (checkIn.Date <= DateTime.Now.Date)
						editLevel = eCom.SalesOrderEditLevel.none;
				}
			}
			return editLevel;
		}

		public void updateReservation(IApplication app, IRuleContext context, object resultValue, object[] inputParams)
		{
			IRuleContext context2 = (IRuleContext)inputParams[1];
			IBizObj salesOrder = inputParams[2] as IBizObj;
			if (salesOrder != null && (bool)ActiveCompany.get("limits.usingReservations") &&
				salesOrder.get("reservation.arrivalDate") != null /* &&
				(app.sessionData.get("makingReservation") is bool && (bool)app.sessionData.get("makingReservation"))*/)
			{
				IBizObj reservation = (IBizObj)salesOrder.get("reservation");
				bool wasResChanged = reservation.isDirty();
				DateTime ad = (DateTime)reservation.get("arrivalDate");
				DateTime dd = (DateTime)reservation.get("departureDate");
				if (dd < ad)
				{
					DateTime t = dd;
					reservation.put("departureDate", dd = ad);
					reservation.put("arrivalDate", ad = t);
				}
				if (reservation.isDirty("numDaysStay"))
				{
					int numDays = (int)reservation.get("numDaysStay");
					if (numDays > 0)
						reservation.put("departureDate", ad + new TimeSpan(numDays, 0, 0, 0, 0));
				}
				else
				{
					TimeSpan t = dd - ad;
					reservation.put("numDaysStay", t.Days);
				}

				bool isValid  = context.RuleGroup.execute(context, "validateReservation", reservation).CallResults == null;

				reservation.clearDirtyFlags();
				if (reservation.isNew)
				{
					reservation.put("id", salesOrder.get("id"));
					reservation.put("madeByBookingAgent", ((IComparable)CurrentUser.get("id")).CompareTo(ActiveCompany.get("anonymousId")) != 0);
					if(isValid)
						app.appData.put("DA.Reservations.AddReservation", reservation);
					if (!Cmn.IsEmpty(reservation.get("flightInfo.arrivalFlightNumber")))
						app.appData.put("DA.Reservations.AddFlightInfo", reservation);
				}
				else
				{
					if(isValid)
						app.appData.put("DA.Reservations.UpdateReservation", reservation);
					app.appData.put("DA.Reservations.DeleteFlightInfo", reservation);
					if (!Cmn.IsEmpty(reservation.get("flightInfo.arrivalFlightNumber")))
						app.appData.put("DA.Reservations.AddFlightInfo", reservation);
					if (wasResChanged)
						context.RuleGroup.execute(context, "recalculateOrderItemPrices", salesOrder);
				}

			}
		}

		public void deleteReservation(IApplication app, IRuleContext context, object resultValue, object[] inputParams)
		{
		}

		public IBizObj getCompanyReservationLimits(IApplication app, IRuleContext context, object returnValue, object[] inputParams)
		{
			IBizObj bizobj = returnValue as IBizObj;
			if (bizobj != null && bizobj.containsField("limits"))
				app.appData.get("DA.Reservations.GetCompanyLimits", bizobj);
			return bizobj;
		}

		public void updateCompanyReservationLimits(IApplication app, IRuleContext context, object returnValue, object[] inputParams)
		{
			try
			{
				IBizObj bizobj = inputParams[2] as IBizObj;
				if (bizobj != null && bizobj.containsField("limits"))
				{
					app.appData.put("DA.Reservations.DeleteCompanyLimits", bizobj.get("limits"));
					app.appData.put("DA.Reservations.AddCompanyLimits", bizobj.get("limits"));
				}
			}
			catch (Exception e)
			{
				throw new BaseException("error executing updateCompanyReservationLimits", e);
			}
		}

		public string getReservationLimitsDisplayTemplate(IApplication app, IRuleContext context, object returnValue, object[] inputParams)
		{
			if (returnValue != null)
			{
				string template = returnValue as string;
				if (ActiveCompany.get("parentId") == null) 
					return template += ",Reservations.Gui.AspNet.LimitsRWDisplay";
				else
					return template;
			}

			return "Articles.Gui.AspNet.LimitsRODisplay";
		}

		public void initiateNewReservation(IApplication app, IRuleContext context)
		{
			if (!(app.sessionData.get("makingReservation") is bool) || !(bool)app.sessionData.get("makingReservation"))
			{
				app.sessionData.put("makingReservation", true);
				IBizObj salesOrder = context.RuleGroup.execute(context, "getCurrentSalesOrderDetails") as IBizObj;
				if (salesOrder == null)
					salesOrder = context.RuleGroup.execute(context, "createNewUserShoppingCart", (INameAddressSupport)null).CallResults as IBizObj;

				if (salesOrder != null)
				{
					IBizObj reservation = (IBizObj)salesOrder.get("reservation");
					reservation.isNew = true;
					reservation.put("id", salesOrder.get("id"));
					reservation.put("arrivalDate", DateTime.Now.Date + new TimeSpan(3, 0, 0, 0, 0));
					reservation.put("departureDate", DateTime.Now.Date + new TimeSpan(8, 0, 0, 0, 0));
					reservation.put("numAdultGuests", 2);
					reservation.put("flightInfo.flightArrival", reservation.get("arrivalDate"));
					reservation.put("flightInfo.flightDeparture", reservation.get("departureDate"));
					context.RuleGroup.execute(context, "updateSalesOrder", salesOrder);
				}
			}
		}

		public void reservationCheckoutComplete(IApplication app, IRuleContext context, object returnValue, object[] inputParams)
		{
			app.sessionData.put("makingReservation", false);
		}
		

		public string getReservationWizardDisplayTemplate(IApplication app, IRuleContext context, IBizObj reservation,
			Privileges editPriv, string parentBPIds, string pageName)
		{
			string templateName = "";
			if (pageName.IndexOf("_admin_") == -1)
			{
				if (app.sessionData.get("makingReservation") is bool && (bool)app.sessionData.get("makingReservation"))
					templateName = "Reservations.Gui.AspNet.SimpleReservationWizardDisplay-Vert";
				else
					templateName = "Reservations.Gui.AspNet.OfferReservationWizardDisplay";
			}
			return templateName;

		}
	}
}
